package org.javacore.base;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author: fanliu
 * @description
 * @date: 2025/4/8 13:59
 */
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;

public class PreciseAverage {

    public static BigDecimal[] calculateStrictAverage(BigDecimal total, int count, int scale) {
        if (count == 0) {
            throw new IllegalArgumentException("Count cannot be zero");
        }

        BigDecimal[] values = new BigDecimal[count];
        BigDecimal average = total.divide(new BigDecimal(count), scale, RoundingMode.HALF_UP);

        // 前 count-1 个值直接用平均值
        for (int i = 0; i < count - 1; i++) {
            values[i] = average;
        }

        // 最后一个值 = total - (average * (count-1))
        BigDecimal remaining = total.subtract(average.multiply(new BigDecimal(count - 1)));
        values[count - 1] = remaining;

        return values;
    }

    public static void main(String[] args) {
        BigDecimal total = new BigDecimal("100.00");
        int count = 3;
        int scale = 2;

        BigDecimal[] values = calculateStrictAverage(total, count, scale);
        System.out.println("分配的值: " + Arrays.toString(values));

        BigDecimal calculatedTotal = Arrays.stream(values).reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println("计算总和: " + calculatedTotal);
        System.out.println("原始总和: " + total);
        System.out.println("是否相等: " + (calculatedTotal.compareTo(total) == 0));
    }
}